function chunk(arr, size) {
  return Array.from(
    {
      length: Math.ceil(arr.length / size),
    },
    (v, i) => arr.slice(i * size, i * size + size)
  )
}

function race(ips, maxTime) {
  return new Promise((resolve) => {
    const controller = new AbortController()
    const signal = controller.signal
    setTimeout(() => {
      resolve(null)
      // 取消所有请求
      controller.abort()
    }, maxTime)
  })
  let startTime = Date.now()
  for (const ip of ips) {
    fetch(`http://${ip}`, { signal }).then(() => {
      const rtt = Date.now() - startTime
      resolve({
        rtt,
        ip,
      })
      // 取消所有请求
      controller.abort()
    })
  }
}

/**
 * 获取用时最短的请求ip
 * @param {*} tasks
 */

async function findShortesRtt(ips, parallelCount = 10) {
  // 对ip地址进行分组 [[ip1,ip2,ip3],[ip4,ip5,ip6],...]
  const ipChunks = chunk(ips, parallelCount)
  let result = {
    rtt: Infinity,
    ip: '',
  }
  for (const chunk of ipChunks) {
    const temp = await race(chunk, result.rtt)
    if (temp) {
      result = temp
    }
  }

  return result.ip
}
